function [trends]=get_trend(x, y, foldername, doplot_trend_funcs, doplot_residuals)

trend1 = polyval( polyfit(x, y, 1), x); 
trend2 = polyval( polyfit(x, y, 2), x);
trend3 = polyval( polyfit(x, y, 3), x);
trend4 = polyval( polyfit(x, y, 4), x);
trend5 = polyval( polyfit(x, y, 4), x);
trend6 = polyval( polyfit(x, y, 6), x);

trends = [trend1, trend2, trend3, trend4, trend5, trend6];

if doplot_trend_funcs == 1 % 1 for plotting trend functions,  0 to skip 
    figure
    whitebg('white'); % sets figure background for pdf to white instead of grey
    set(gcf, 'PaperOrientation', 'landscape');
    %set(gcf, 'PaperPositionMode', 'manual');
    set(gcf, 'PaperUnits', 'inches');
    set(gcf, 'PaperType', 'usletter');
    set(gcf, 'PaperPosition', [0 0 11.5 8]);
    hold on
    grid
    title('Average Elevation and trend functions')
    plot(x, y, 'k');
    plot(x, trend1, 'c');
    plot(x, trend2, 'g');
    plot(x, trend3, 'r');
    plot(x, trend4, 'm');
    plot(x, trend6, 'b');
    legend('avg. elev.', 'trend order 1', 'trend order 2','trend order 3','trend order 4', 'trend order 6')
    filename = 'avg_elev_and_trend_functions'%
    fullname = fullfile(foldername, filename);
    saveas(gcf, [fullname '.pdf']);
end

if doplot_residuals == 1 % 1 for plotting residuals ,  0 to skip 
    figure
    whitebg('white'); % sets figure background for pdf to white instead of grey
    set(gcf, 'PaperOrientation', 'landscape');
    %set(gcf, 'PaperPositionMode', 'manual');
    set(gcf, 'PaperUnits', 'inches');
    set(gcf, 'PaperType', 'usletter');
    set(gcf, 'PaperPosition', [0 0 11.5 8]);
    hold on
    grid
    title('Average Elevation and residuals after trend removal (with variance captured)')
    res1 = y-trend1; % residual (error)
    res2 = y-trend2;
    res3 = y-trend3;
    res4 = y-trend4;
    res6 = y-trend6;

    plot(x, y-mean(y), 'k')
    plot(x, res1, 'c');
    plot(x, res2, 'g');
    plot(x, res3, 'r');
    plot(x, res4, 'm');
    plot(x, res6, 'b');

    r_sq1 = 1 - var(res1) / var(y);
    r_sq2 = 1 - var(res2) / var(y);
    r_sq3 = 1 - var(res3) / var(y);
    r_sq4 = 1 - var(res4) / var(y);
    r_sq6 = 1 - var(res6) / var(y);

    legend('avg. elev. (de-meaned)', ...
           sprintf('trend order 1 removed, %.3f', r_sq1), ...
           sprintf('trend order 2 removed, %.3f', r_sq2), ...
           sprintf('trend order 3 removed, %.3f', r_sq3), ...
           sprintf('trend order 4 removed, %.3f', r_sq4), ...
           sprintf('trend order 6 removed, %.3f', r_sq6))
    filename = 'avg_elev_and_residuals'%
    fullname = fullfile(foldername, filename);
    saveas(gcf, [fullname '.pdf']);
end
  
